<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="applicantIdNumber">
        <el-input
          v-model="queryParams.applicantIdNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="异议类型" prop="objectionType">
        <el-select
          v-model="queryParams.objectionType"
          placeholder="请选择异议类型"
          clearable
          class="!w-240px"
        >
          <el-option label="成绩异议" value="score" />
          <el-option label="资格异议" value="qualification" />
          <el-option label="程序异议" value="procedure" />
          <el-option label="其他异议" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="handleStatus">
        <el-select
          v-model="queryParams.handleStatus"
          placeholder="请选择处理状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待处理" :value="0" />
          <el-option label="处理中" :value="1" />
          <el-option label="已处理" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择关联计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:objection:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:objection:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总异议数</div>
          </div>
          <Icon icon="ep:document" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.pendingCount || 0 }}</div>
            <div class="text-gray-500">待处理</div>
          </div>
          <Icon icon="ep:clock" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.processedCount || 0 }}</div>
            <div class="text-gray-500">已处理</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ statistics.rejectedCount || 0 }}</div>
            <div class="text-gray-500">已驳回</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="申请人" align="center" prop="applicantName" width="100" />
      <el-table-column label="身份证号" align="center" prop="applicantIdNumber" width="180" />
      <el-table-column label="联系电话" align="center" prop="applicantPhone" width="120" />
      <el-table-column label="关联计划" align="center" prop="planName" width="150" />
      <el-table-column label="异议类型" align="center" prop="objectionType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_OBJECTION_TYPE" :value="scope.row.objectionType" />
        </template>
      </el-table-column>
      <el-table-column label="异议内容" align="center" prop="objectionContent" width="200" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.applicationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="handleStatus" width="100">
        <template #default="scope">
          <el-tag :type="getHandleStatusTagType(scope.row.handleStatus)">
            {{ getHandleStatusText(scope.row.handleStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="handlerName" width="100" />
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template #default="scope">
          {{ scope.row.handleTime ? formatDateTime(scope.row.handleTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:objection:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:objection:update']"
            v-if="scope.row.handleStatus < 2"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="handle" v-if="scope.row.handleStatus === 0">
                  处理
                </el-dropdown-item>
                <el-dropdown-item command="reject" v-if="scope.row.handleStatus < 2">
                  驳回
                </el-dropdown-item>
                <el-dropdown-item command="timeline">
                  处理记录
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.handleStatus === 0">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ObjectionForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <ObjectionDetail ref="detailRef" />
  
  <!-- 处理弹窗 -->
  <ObjectionHandle ref="handleRef" @success="getList" />
  
  <!-- 驳回弹窗 -->
  <ObjectionReject ref="rejectRef" @success="getList" />
  
  <!-- 处理记录弹窗 -->
  <ObjectionTimeline ref="timelineRef" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDateTime } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalObjectionVO, 
  EvalObjectionPageReqVO, 
  getObjectionPage, 
  deleteObjection, 
  exportObjection 
} from '@/api/eval/objection'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import ObjectionForm from './ObjectionForm.vue'
import ObjectionDetail from './ObjectionDetail.vue'
import ObjectionHandle from './ObjectionHandle.vue'
import ObjectionReject from './ObjectionReject.vue'
import ObjectionTimeline from './ObjectionTimeline.vue'

/** 异议处理 列表 */
defineOptions({ name: 'EvalObjection' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalObjectionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const queryParams = reactive<EvalObjectionPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  applicantName: undefined,
  applicantIdNumber: undefined,
  objectionType: undefined,
  handleStatus: undefined,
  planId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getObjectionPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 计算统计数据
    calculateStatistics()
  } finally {
    loading.value = false
  }
}

/** 计算统计数据 */
const calculateStatistics = () => {
  const totalCount = list.value.length
  const pendingCount = list.value.filter(item => item.handleStatus === 0).length
  const processedCount = list.value.filter(item => item.handleStatus === 2).length
  const rejectedCount = list.value.filter(item => item.handleStatus === 3).length
  
  statistics.value = {
    totalCount,
    pendingCount,
    processedCount,
    rejectedCount
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 处理操作 */
const handleRef = ref()
const openHandle = (id: number) => {
  handleRef.value.open(id)
}

/** 驳回操作 */
const rejectRef = ref()
const openReject = (id: number) => {
  rejectRef.value.open(id)
}

/** 处理记录操作 */
const timelineRef = ref()
const openTimeline = (id: number) => {
  timelineRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalObjectionVO) => {
  switch (command) {
    case 'handle':
      openHandle(row.id!)
      break
    case 'reject':
      openReject(row.id!)
      break
    case 'timeline':
      openTimeline(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteObjection(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportObjection(queryParams)
    download.excel(data, '异议处理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取处理状态标签类型 */
const getHandleStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'primary', 2: 'success', 3: 'danger' }
  return typeMap[status] || ''
}

/** 获取处理状态文本 */
const getHandleStatusText = (status: number) => {
  const textMap = { 0: '待处理', 1: '处理中', 2: '已处理', 3: '已驳回' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取所有状态的计划
    const allPlans = await Promise.all([
      getPlanListByStatus(3), // 已发布
      getPlanListByStatus(4), // 进行中
      getPlanListByStatus(5)  // 已完成
    ])
    planList.value = allPlans.flat()
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
